package cc.eddic.practice.spring.webapi;

import cc.eddic.practice.spring.dto.StudentAddRequest;
import cc.eddic.practice.spring.dto.StudentResponse;
import cc.eddic.practice.spring.repository.StudentRepository;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

import java.util.List;
import java.util.NoSuchElementException;

@Slf4j
@RestController
@RequestMapping("/api/students")
public class StudentRestController {
    public StudentRestController(StudentRepository repository) {
        this.repository = repository;
    }

    @PostMapping
    public HttpEntity<?> add(@RequestBody final StudentAddRequest model) {
        val student = repository.save(model.as());
        return ResponseEntity.created(ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(student.getId()).toUri()).build();
    }

    @DeleteMapping("/{id}")
    public HttpEntity<?> del(@PathVariable("id") final long id) {
        repository.deleteById(id);
        return ResponseEntity.noContent().build();
    }

    @DeleteMapping
    public HttpEntity<?> del(@RequestParam("id") final List<Long> ids) {
        repository.deleteAllById(ids);
        return ResponseEntity.noContent().build();
    }

    @GetMapping("/{id}")
    public HttpEntity<StudentResponse> get(@PathVariable("id") final long id) {
        if (log.isDebugEnabled()) log.debug("id = {}", id);
        val student = repository.findById(id).orElseThrow(NoSuchElementException::new);
        return ResponseEntity.ok(StudentResponse.from(student));
    }

    @GetMapping
    public HttpEntity<Page<StudentResponse>> getAll(@PageableDefault(size = 1, page = 0) Pageable pageable) {
        log.debug("size = {}, page = {}", pageable.getPageSize(), pageable.getPageNumber());

//        val students = repository.findAll(pageable).stream().map(StudentResponse::from).collect(Collectors.toList());
        return ResponseEntity.ok(repository.findAll(pageable).map(StudentResponse::from));
    }

    private final StudentRepository repository;
}
